<template>
  <div :style="{height:'400px',width:'100%'}"></div>
</template>

<script>
  /* eslint-disable */
  import echarts from 'echarts'
  import moment from 'moment'
  import { debounce } from '@/utils'

  export default {
    props: {
      chartData: {
        type: Array,
        default: []
      }
    },
    data() {
      return {
        autoResize: true,
        chart: null,
      }
    },
    mounted() {
      this.initChart()
      if (this.autoResize) {
        this.__resizeHanlder = debounce(() => {
          if (this.chart) {
            this.chart.resize()
          }
        }, 100)
        window.addEventListener('resize', this.__resizeHanlder)
      }
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      if (this.autoResize) {
        window.removeEventListener('resize', this.__resizeHanlder)
      }

      this.chart.dispose()
      this.chart = null
    },
    watch: {
      chartData: {
        deep: true,
        handler(val) {
          this.setOptions(val)
        }
      }
    },
    methods: {
      setOptions(chartData) {
        console.log(chartData)
        this.chart.setOption({
          xAxis: {
            data: chartData.map((item) => moment(item.time).format('HH:mm:ss')),
            boundaryGap: false,
            axisTick: {
              show: false
            }
          },
          grid: {
            left: 10,
            right: 10,
            bottom: 20,
            top: 30,
            containLabel: true
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
            },
            padding: [5, 10]
          },
          yAxis: {
            axisTick: {
              show: false
            }
          },
          legend: {
            data: ['成绩统计']
          },
          series: [
            {
              name: '成绩统计',
              smooth: true,
              type: 'line',
              itemStyle: {
                normal: {
                  color: '#3888fa',
                  lineStyle: {
                    color: '#3888fa',
                    width: 2
                  },
                  areaStyle: {
                    color: '#f3f8ff'
                  }
                }
              },
              data: chartData.map(item => parseInt(item.score)),
              animationDuration: 2800,
              animationEasing: 'quadraticOut'
            }]
        })
      },
      initChart() {
        this.chart = echarts.init(this.$el)
        this.setOptions(this.chartData)
      }
    }
  }
</script>
